<template>
  <div class="file-upload-test">
    <div class="test-header">
      <h1>文件上传兼容性测试</h1>
      <p>测试各种文件上传场景的浏览器兼容性</p>
    </div>

    <div class="test-sections">
      <!-- 1. 原始Ant Design Upload测试 -->
      <div class="test-section">
        <h2>1. Ant Design Upload 组件</h2>
        <a-upload
          :show-upload-list="false"
          :before-upload="beforeUpload"
          :custom-request="customUpload"
          accept="image/*"
        >
          <a-button type="primary">
            <UploadOutlined />
            选择图片 (Ant Design)
          </a-button>
        </a-upload>
        <div v-if="antUploadResult" class="result">
          结果: {{ antUploadResult }}
        </div>
      </div>

      <!-- 2. 自定义FileUpload组件测试 -->
      <div class="test-section">
        <h2>2. 自定义 FileUpload 组件</h2>
        <FileUpload
          accept="image/*"
          :loading="customUploadLoading"
          @file-selected="handleCustomFileSelected"
          @file-error="handleCustomFileError"
        >
          <a-button type="default">
            <UploadOutlined />
            选择图片 (自定义组件)
          </a-button>
        </FileUpload>
        <div v-if="customUploadResult" class="result">
          结果: {{ customUploadResult }}
        </div>
      </div>

      <!-- 3. AvatarUpload组件测试 -->
      <div class="test-section">
        <h2>3. AvatarUpload 组件</h2>
        <AvatarUpload
          v-model="avatarUrl"
          :size="120"
          fallback-text="测试"
          @upload-success="handleAvatarUploadSuccess"
          @upload-error="handleAvatarUploadError"
        />
        <div v-if="avatarUploadResult" class="result">
          结果: {{ avatarUploadResult }}
        </div>
      </div>

      <!-- 4. 原生input测试 -->
      <div class="test-section">
        <h2>4. 原生 Input 元素</h2>
        <input
          ref="nativeInputRef"
          type="file"
          accept="image/*"
          style="display: none"
          @change="handleNativeInputChange"
        />
        <a-button @click="triggerNativeInput">
          <UploadOutlined />
          选择图片 (原生Input)
        </a-button>
        <div v-if="nativeInputResult" class="result">
          结果: {{ nativeInputResult }}
        </div>
      </div>

      <!-- 5. 拖拽上传测试 -->
      <div class="test-section">
        <h2>5. 拖拽上传</h2>
        <FileUpload
          accept="image/*"
          enable-drop
          :loading="dragUploadLoading"
          @file-selected="handleDragFileSelected"
          @file-error="handleDragFileError"
        >
          <div class="drag-upload-area">
            <UploadOutlined style="font-size: 24px; margin-bottom: 8px;" />
            <div>点击选择或拖拽图片到此处</div>
          </div>
        </FileUpload>
        <div v-if="dragUploadResult" class="result">
          结果: {{ dragUploadResult }}
        </div>
      </div>
    </div>

    <!-- 浏览器信息 -->
    <div class="browser-info">
      <h3>浏览器信息</h3>
      <div class="info-grid">
        <div class="info-item">
          <strong>User Agent:</strong>
          <span>{{ browserInfo.userAgent }}</span>
        </div>
        <div class="info-item">
          <strong>浏览器:</strong>
          <span>{{ browserInfo.browser }}</span>
        </div>
        <div class="info-item">
          <strong>版本:</strong>
          <span>{{ browserInfo.version }}</span>
        </div>
        <div class="info-item">
          <strong>操作系统:</strong>
          <span>{{ browserInfo.os }}</span>
        </div>
        <div class="info-item">
          <strong>文件API支持:</strong>
          <span :class="{ 'supported': browserInfo.fileApiSupported, 'not-supported': !browserInfo.fileApiSupported }">
            {{ browserInfo.fileApiSupported ? '✅ 支持' : '❌ 不支持' }}
          </span>
        </div>
      </div>
    </div>

    <!-- 测试日志 -->
    <div class="test-logs">
      <h3>测试日志</h3>
      <div class="logs-container">
        <div
          v-for="(log, index) in testLogs"
          :key="index"
          class="log-item"
          :class="log.type"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </div>
      </div>
      <a-button @click="clearLogs" size="small">清空日志</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import FileUpload from '@/components/FileUpload.vue'
import AvatarUpload from '@/components/AvatarUpload.vue'
import { apiService } from '@/services/api'

// 测试结果
const antUploadResult = ref('')
const customUploadResult = ref('')
const avatarUploadResult = ref('')
const nativeInputResult = ref('')
const dragUploadResult = ref('')

// 加载状态
const customUploadLoading = ref(false)
const dragUploadLoading = ref(false)

// 头像URL
const avatarUrl = ref('')

// 原生input引用
const nativeInputRef = ref<HTMLInputElement>()

// 测试日志
interface TestLog {
  time: string
  message: string
  type: 'info' | 'success' | 'error' | 'warning'
}

const testLogs = ref<TestLog[]>([])

// 浏览器信息
const browserInfo = reactive({
  userAgent: '',
  browser: '',
  version: '',
  os: '',
  fileApiSupported: false
})

// 添加日志
const addLog = (message: string, type: TestLog['type'] = 'info') => {
  testLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message,
    type
  })
}

// 清空日志
const clearLogs = () => {
  testLogs.value = []
}

// 检测浏览器信息
const detectBrowserInfo = () => {
  const ua = navigator.userAgent
  browserInfo.userAgent = ua

  // 检测浏览器
  if (ua.includes('Chrome')) {
    browserInfo.browser = 'Chrome'
    const match = ua.match(/Chrome\/(\d+)/)
    browserInfo.version = match ? match[1] : 'Unknown'
  } else if (ua.includes('Firefox')) {
    browserInfo.browser = 'Firefox'
    const match = ua.match(/Firefox\/(\d+)/)
    browserInfo.version = match ? match[1] : 'Unknown'
  } else if (ua.includes('Safari') && !ua.includes('Chrome')) {
    browserInfo.browser = 'Safari'
    const match = ua.match(/Version\/(\d+)/)
    browserInfo.version = match ? match[1] : 'Unknown'
  } else if (ua.includes('Edge')) {
    browserInfo.browser = 'Edge'
    const match = ua.match(/Edge\/(\d+)/)
    browserInfo.version = match ? match[1] : 'Unknown'
  } else {
    browserInfo.browser = 'Unknown'
    browserInfo.version = 'Unknown'
  }

  // 检测操作系统
  if (ua.includes('Windows')) {
    browserInfo.os = 'Windows'
  } else if (ua.includes('Mac')) {
    browserInfo.os = 'macOS'
  } else if (ua.includes('Linux')) {
    browserInfo.os = 'Linux'
  } else if (ua.includes('Android')) {
    browserInfo.os = 'Android'
  } else if (ua.includes('iOS')) {
    browserInfo.os = 'iOS'
  } else {
    browserInfo.os = 'Unknown'
  }

  // 检测文件API支持
  browserInfo.fileApiSupported = !!(window.File && window.FileReader && window.FileList && window.Blob)
}

// Ant Design Upload 处理
const beforeUpload = (file: File) => {
  addLog(`Ant Design Upload - beforeUpload: ${file.name}`, 'info')
  return true
}

const customUpload = async (options: any) => {
  const { file } = options
  addLog(`Ant Design Upload - customUpload: ${file.name}`, 'info')
  
  try {
    const result = await apiService.uploadAvatar(file)
    antUploadResult.value = `成功上传: ${result.fileName}`
    addLog(`Ant Design Upload - 上传成功: ${result.fileName}`, 'success')
    options.onSuccess(result)
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '上传失败'
    antUploadResult.value = `上传失败: ${errorMsg}`
    addLog(`Ant Design Upload - 上传失败: ${errorMsg}`, 'error')
    options.onError(error)
  }
}

// 自定义FileUpload处理
const handleCustomFileSelected = async (files: File[]) => {
  const file = files[0]
  addLog(`自定义FileUpload - 文件选择: ${file.name}`, 'info')
  
  customUploadLoading.value = true
  try {
    const result = await apiService.uploadAvatar(file)
    customUploadResult.value = `成功上传: ${result.fileName}`
    addLog(`自定义FileUpload - 上传成功: ${result.fileName}`, 'success')
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '上传失败'
    customUploadResult.value = `上传失败: ${errorMsg}`
    addLog(`自定义FileUpload - 上传失败: ${errorMsg}`, 'error')
  } finally {
    customUploadLoading.value = false
  }
}

const handleCustomFileError = (error: string) => {
  customUploadResult.value = `文件错误: ${error}`
  addLog(`自定义FileUpload - 文件错误: ${error}`, 'error')
}

// AvatarUpload处理
const handleAvatarUploadSuccess = (result: any) => {
  avatarUploadResult.value = `成功上传: ${result.fileName}`
  addLog(`AvatarUpload - 上传成功: ${result.fileName}`, 'success')
}

const handleAvatarUploadError = (error: string) => {
  avatarUploadResult.value = `上传失败: ${error}`
  addLog(`AvatarUpload - 上传失败: ${error}`, 'error')
}

// 原生Input处理
const triggerNativeInput = () => {
  addLog('原生Input - 触发文件选择', 'info')
  nativeInputRef.value?.click()
}

const handleNativeInputChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  addLog(`原生Input - 文件选择: ${file.name}`, 'info')
  
  try {
    const result = await apiService.uploadAvatar(file)
    nativeInputResult.value = `成功上传: ${result.fileName}`
    addLog(`原生Input - 上传成功: ${result.fileName}`, 'success')
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '上传失败'
    nativeInputResult.value = `上传失败: ${errorMsg}`
    addLog(`原生Input - 上传失败: ${errorMsg}`, 'error')
  }
  
  // 清空input值
  target.value = ''
}

// 拖拽上传处理
const handleDragFileSelected = async (files: File[]) => {
  const file = files[0]
  addLog(`拖拽上传 - 文件选择: ${file.name}`, 'info')
  
  dragUploadLoading.value = true
  try {
    const result = await apiService.uploadAvatar(file)
    dragUploadResult.value = `成功上传: ${result.fileName}`
    addLog(`拖拽上传 - 上传成功: ${result.fileName}`, 'success')
  } catch (error: any) {
    const errorMsg = error.response?.data?.message || '上传失败'
    dragUploadResult.value = `上传失败: ${errorMsg}`
    addLog(`拖拽上传 - 上传失败: ${errorMsg}`, 'error')
  } finally {
    dragUploadLoading.value = false
  }
}

const handleDragFileError = (error: string) => {
  dragUploadResult.value = `文件错误: ${error}`
  addLog(`拖拽上传 - 文件错误: ${error}`, 'error')
}

onMounted(() => {
  detectBrowserInfo()
  addLog('页面加载完成，开始兼容性测试', 'info')
})
</script>

<style scoped>
.file-upload-test {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-header {
  text-align: center;
  margin-bottom: 40px;
}

.test-header h1 {
  color: #1890ff;
  margin-bottom: 8px;
}

.test-sections {
  display: grid;
  gap: 30px;
  margin-bottom: 40px;
}

.test-section {
  padding: 20px;
  border: 1px solid #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
}

.test-section h2 {
  margin-bottom: 16px;
  color: #333;
}

.result {
  margin-top: 12px;
  padding: 8px 12px;
  background: #f0f0f0;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
}

.drag-upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  text-align: center;
  transition: all 0.3s ease;
}

.drag-upload-area:hover {
  border-color: #1890ff;
  background: #e6f7ff;
}

.browser-info {
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.browser-info h3 {
  margin-bottom: 16px;
  color: #333;
}

.info-grid {
  display: grid;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item strong {
  min-width: 100px;
  color: #666;
}

.supported {
  color: #52c41a;
}

.not-supported {
  color: #ff4d4f;
}

.test-logs {
  padding: 20px;
  background: #f5f5f5;
  border-radius: 8px;
}

.test-logs h3 {
  margin-bottom: 16px;
  color: #333;
}

.logs-container {
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 12px;
  padding: 12px;
  background: white;
  border-radius: 4px;
  border: 1px solid #d9d9d9;
}

.log-item {
  display: flex;
  gap: 12px;
  padding: 4px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
  font-family: monospace;
}

.log-item:last-child {
  border-bottom: none;
}

.log-time {
  color: #666;
  min-width: 80px;
}

.log-message {
  flex: 1;
}

.log-item.info .log-message {
  color: #333;
}

.log-item.success .log-message {
  color: #52c41a;
}

.log-item.error .log-message {
  color: #ff4d4f;
}

.log-item.warning .log-message {
  color: #faad14;
}
</style>
